<template>
	<view class="page-wapper">

		<view class="page-content">

			<u-form ref="formdom" label-position="top" errorType="toast" :model="state.formdata" :rules="rules">
				<view class="form-title">
					资料
				</view>
				<u-form-item prop="category_id">
					<view class="inputwapper" style="width: 100%;">
						<view class="label">
							<span>*</span>分类
						</view>
						<view class="ss-flex flex-1" style="flex:1;" @tap="state.pickshow=true">
							<text>{{state.typeinfo||'选择分类'}}</text>
							<u-icon name="arrow-right" style="margin-left: auto;"></u-icon>
						</view>
				
					</view>
				</u-form-item>
				<u-form-item prop="title">
					<view class="inputwapper">
						<view class="label">
							<span>*</span>标题
						</view>
						<input type="text" placeholder="请输入标题" v-model="state.formdata.title" />
				
					</view>
				</u-form-item>
				<u-form-item prop="brief">
					<view class="inputwapper ss-flex-col" style="align-items: flex-start;">
						<view class="label">
							<span>*</span>内容介绍
						</view>
						<sp-editor style="height: 800rpx;width: 100%;" :toolbar-config="{
						          excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
						          iconSize: '18px'
						        }" @init="initEditor1" @input="inputOver1" @upinImage="upinImage1" @overMax="overMax1" @addLink="addLink"
							@exportHtml="exportHtml" :key="1" id1='s1'></sp-editor>
				
					</view>
				</u-form-item>
				

				<view class="form-title">
					付费内容
				</view>
				<u-form-item prop="content">

					<sp-editor id1='s2' :key="2" style="height: 800rpx;width: 100%;" :toolbar-config="{
					          excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
					          iconSize: '18px'
					        }" @init="initEditor" @input="inputOver" @upinImage="upinImage" @overMax="overMax" @addLink="addLink"
						@exportHtml="exportHtml"></sp-editor>
				</u-form-item>
				<u-form-item prop="price">
					<view class="inputwapper">
						<view class="label">
							<span>*</span>价格
						</view>
						<input type="text" placeholder="请输入价格" v-model="state.formdata.price" />
				
					</view>
				</u-form-item>





			</u-form>

			<view class="" style="height: 30rpx;">

			</view>
			<u-picker :show="state.pickshow"    keyName="name" ref="uPicker" @cancel="()=>{state.pickshow=false}" :columns="[cpcategory,cpcategorylist[cpcategory[0].id]]" @confirm="confirm" @change="changeHandler"></u-picker>
			<button class="button" @tap="onsubmit" v-if="state.obj.status!=1">提交</button>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		reactive,
		ref,
		onMounted,
		getCurrentInstance,
		nextTick
	} from 'vue';
	import {
		onLoad,
		onReady,
		onReachBottom
	} from '@dcloudio/uni-app'
	import LC from '@/LC'
	let state = reactive({
		pickshow:false,
		formdata: {
			category_id: '',
			title: '',
			price: '',
			brief: '',
			
			content: '',

		},
		id:null,
		defindex:[0,0],
		typeinfo:'',
		editorIns: null,
		editorIns1: null,
		obj: {},

		data: []
	})


	let info = computed(() => LC.$store('user').info)
	let cpcategory = computed(() => LC.$store('app').cpcategory)
	let cpcategorylist = computed(() => LC.$store('app').cpcategorylist)
	const rules = {
		price: [{
			required: true,
			message: '请输入价格',
			trigger: ['blur', 'change']
		},
		{
			type:'number',
			message: '请输入价格',
			min:0,
			trigger: ['blur', 'change']
		}
		],
		title: [{
			required: true,
			message: '请填入标题',
			trigger: ['blur', 'change']
		}],
		brief: [{
			required: true,
			message: '请填入简介',
			trigger: ['blur', 'change']
		}],
		content: [{
			required: true,
			message: '请填入付费内容',
			trigger: ['blur', 'change']
		}],
		


	}
	let avatar = computed(() => {
		if (state.formdata.avatar_full) {
			return state.formdata.avatar_full
		}

	})
	onLoad(({id})=>{
		
		if(!id){
			 state.defindex=uni.getStorageSync('defindex')||[0,0] 
			 confirm({value:[cpcategory.value[state.defindex[0]],cpcategorylist.value[cpcategory.value[state.defindex[0]].id][state.defindex[0]]],indexs:state.defindex}) 
			
		}
		if(id){
		state.id=id	
		}
		
	})
	let uPicker1=ref(null)
	function  changeHandler(e) {
		const {
			columnIndex,
			value,
			values, // values为当前变化列的数组内容
			index,
			// 微信小程序无法将picker实例传出来，只能通过ref操作
			picker 
		} = e
		// 当第一列值发生变化时，变化第二列(后一列)对应的选项
		if (columnIndex === 0) {
			// picker为选择器this实例，变化第二列对应的选项
			
			picker.setColumnValues(1,  cpcategorylist.value[value[0].id])
			return 
		}
		
	}
	// 回调参数为包含columnIndex、value、values
	function confirm({value,indexs}) {
		console.log(value,indexs)
		state.defindex=indexs
		state.typeinfo=value[0].name+'-'+value[1].name
		state.formdata.category_id= value[1].id
		state.pickshow=false
	}
	onMounted(() => {
		
	})

	function getPathFromURL(url) {
		try {
			const urlObj = new URL(url);
			return urlObj.pathname;
		} catch (e) {
			console.error(e.message);
			return null;
		}
	}
	


	let formdom = ref(null)

	function onsubmit() {

		formdom.value.validate().then(res => {
			send()
		}).catch(err => {
			formdom.value.clearValidate()

			console.log('表单错误信息：', err);
		})
	}

	function parse() {
		uni.getClipboardData({
			success: function(res) {
				state.formdata.address = res.data
				// 粘贴到文本框中

			}
		})
	}
	function getindex (type) {
		
		for(let key  in  cpcategorylist.value) {
			
			cpcategorylist.value[key].forEach((a,index)=>{
				if(a.id===type){
					console.log(index)
					state.defindex[1]=index
					cpcategory.value.forEach((a,index1)=>{
						console.log(a.id,key)
						if(a.id===key*1){
							state.defindex[0]=index1
						}
					})
				}
			})
		}
		console.log(state.defindex)
		 confirm({value:[cpcategory.value[state.defindex[0]],cpcategorylist.value[cpcategory.value[state.defindex[0]].id][state.defindex[0]]],indexs:state.defindex}) 
	}
	async function send() {
		
		if(state.id){
			const res = await LC.$api.user.articleedit({id:state.id,...state.formdata})
			if (res.code == 1) {
				LC.$store('user').userinfo()
				uni.$emit('updata')
				uni.navigateBack({
					success() {
						uni.$u.toast('发布成功')
					}
				})
			
			
			}
			return
		}
		const res = await LC.$api.user.articleadd(state.formdata)
		uni.setStorageSync('defindex',state.defindex)
		if (res.code == 1) {
			uni.$emit('updata')
			LC.$store('user').userinfo()
			uni.navigateBack({
				success() {
					uni.$u.toast('发布成功')
				}
			})


		}
	




	}


	function upimg(key) {
		uni.chooseImage({
			success: async (chooseImageRes) => {
				const tempUrl = chooseImageRes.tempFilePaths[0];
				uploadPay_image(tempUrl, key);
			},
		});
	}
	async function uploadPay_image(tempUrl, key) {
		if (!tempUrl) return;
		let {
			url,
			fullurl
		} = await LC.$api.app.upload(tempUrl, 'ugc');
		state.formdata[key] = url;
		state.formdata[key + '_full'] = fullurl;
		console.log(state.formdata)
	}
















	function inputOver(e) {
		// 可以在此处获取到编辑器已编辑的内容
		
		state.formdata.content=e.html
	}
	function inputOver1(e) {
	
		// 可以在此处获取到编辑器已编辑的内容
		state.formdata.brief=e.html
	}
	/**
	 * 超出最大内容限制
	 * @param {Object} e {html,text} 内容的html文本，和text文本
	 */
	function overMax(e) {
		// 若设置了最大字数限制，可在此处触发超出限制的回调
		console.log('==== overMax :', e)
	}
	function overMax1(e) {
		// 若设置了最大字数限制，可在此处触发超出限制的回调
		console.log('==== overMax :', e)
	}
	/**
	 * 编辑器就绪
	 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
	 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
	 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
	 */
	async function initEditor(editor) {
		
		state.editorIns = editor // 保存编辑器实例
		// console.log(state.editorIns,state.editorIns1)
		// 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
		if(state.id){
			const res = await LC.$api.user.articleshow({id:state.id})
			uni.setNavigationBarTitle({
				title:'编辑文章'
			})
			if (res.code == 1) {
				state.formdata.title=res.data.title
			state.formdata.price=res.data.price
			// state.formdata.brief=res.data.brief
			preRender(res.data.content)
			}
			
			
			
		}
		
	}
	async function initEditor1(editor) {
		
		state.editorIns1 = editor // 保存编辑器实例
		// 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
		if(state.id){
			const res = await LC.$api.user.articleshow({id:state.id})
			uni.setNavigationBarTitle({
				title:'编辑文章'
			})
			if (res.code == 1) {
				getindex(res.data.category_id)
				state.formdata.title=res.data.title
			state.formdata.price=res.data.price
			
			preRender1(res.data.brief)
			}
			
			
			
		}
		
	}

	function preRender(a) {
		setTimeout(() => {
			// 异步获取后端数据后，初始化编辑器内容
			state.editorIns.setContents({
				html: a
			})
			state.formdata.content=a
		}, 1000)
	}
	function preRender1(a) {
		setTimeout(() => {
			// 异步获取后端数据后，初始化编辑器内容
			state.editorIns1.setContents({
				html: a
			})
			state.formdata.brief=a
		}, 1000)
	}
	/**
	 * 直接运行示例工程插入图片无法正常显示的看这里
	 * 因为插件默认采用云端存储图片的方式
	 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
	 * @param {Object} tempFiles
	 * @param {Object} editorCtx
	 */
	function upinImage(tempFiles, editorCtx) {

		tempFiles.forEach(async (item) => {
			uni.showLoading({
				title: '上传中请稍后',
				mask: true
			})

			let {
				url,
				fullurl
			} = await LC.$api.app.upload(item.path, 'ugc');
			

			editorCtx.insertImage({
				src: fullurl,
				width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
				success: function() {
					uni.hideLoading()
				}
			})
		})
	}
	function upinImage1(tempFiles, editorCtx) {
	
		tempFiles.forEach(async (item) => {
			uni.showLoading({
				title: '上传中请稍后',
				mask: true
			})
	
			let {
				url,
				fullurl
			} = await LC.$api.app.upload(item.path, 'ugc');
			
	
			editorCtx.insertImage({
				src: fullurl,
				width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
				success: function() {
					uni.hideLoading()
				}
			})
		})
	}
	/**
	 * 导出 - toolbar需要开启export工具
	 * @param {string} e 导出的html内容
	 */
	function exportHtml(e) {
		uni.navigateTo({
			url: '/pages/out/out',
			success(res) {
				// 传至导出页面解析即可
				res.eventChannel.emit('e-transmit-html', {
					data: e
				})
			}
		})
	}

	/**
	 * 添加超链接
	 * @param {Object} e { text: '链接描述', href: '链接地址' }
	 */
	function addLink(e) {
		console.log('==== addLink :', e)
	}
</script>

<style lang="scss" scoped>
	.tip {

		height: 104rpx;
		padding: 16rpx 30rpx;
		margin: 20rpx 30rpx;
		background: #fefbea;
		font-size: 20rpx;
		font-weight: 400;
	}

	.textarea {
		background: rgb(248, 248, 248);
		margin: 0 30rpx;
	}

	.form-title {

		height: 84rpx;
		background: #f8f8f8;
		padding: 0 30rpx;
		font-size: 24rpx;
		font-weight: 500;
		color: #666;
		line-height: 84rpx;
	}

	.img-wapper {
		padding: 55rpx 21rpx;
		background: #FFFFFF;
		align-items: stretch;
		border-radius: 15rpx;

		width: 100%;

		.left {
			.title1 {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 31rpx;
				color: #333333;
				line-height: 42rpx;
			}

			.title2 {
				margin-top: 10rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 23rpx;
				color: #999999;
			}
		}

		.icon {
			width: 383rpx;
			height: 240rpx;
			margin-left: auto;
		}
	}

	::v-deep .u-form-item__body {
		padding: 0rpx 0;
	}

	.button {


		height: 86rpx;
		flex-shrink: 0;
		margin: 0 30rpx;
		background-color: #FC5652;
		border-radius: 15rpx;
		font-weight: 400;
		font-size: 31rpx;

		line-height: 86rpx;
		color: #fff;

		margin-top: auto;

		&.dis {
			background-color: #CCCCCC;
		}

		&::after {
			display: none;
		}


	}

	.inputwapper {
		display: flex;
		width: 100%;
		align-items: center;
		padding: 31rpx 23rpx;
		background: #FFFFFF;
		border-bottom: 2rpx solid #e4e4e4;
		border-radius: 15rpx;

		.icon {
			margin-left: auto;
			width: 53rpx;
			height: 53rpx;
		}

		.label {
			width: 135rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 800;
			font-size: 27rpx;
			color: #111;
			line-height: 38rpx;

			span {
				color: red;
			}

		}

		input {
			flex: 1;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 27rpx;
			color: #333;
		}
	}

	.tab {
		margin-bottom: 10rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 27rpx;
		color: #999999;
		line-height: 38rpx;

		.tabitem {
			margin-right: 30rpx;
		}

		.active {
			font-weight: 600;
			color: #333333;
		}
	}

	.left-icon {
		display: flex;
		width: 41rpx;
		height: 42rpx;
	}

	.page-wapper {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.page-content {
		flex: 1;
		display: flex;
		flex-direction: column;

		padding-top: 10rpx;
	}
</style>